﻿using System.Collections.Generic;
using System.Linq;
using Microsoft.Practices.EnterpriseLibrary.Validation.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Validation.Validators;
using System;

namespace AsNum.Common.EntLib.Validation.Adapters {
    public class PropertyComparisonClientAdapter : BaseClientAdapter<PropertyComparisonValidatorData> {

        public PropertyComparisonClientAdapter(PropertyComparisonValidatorData data , Dictionary<string , Tuple<string , string>> map , bool isSub = false)
            : base ( data , map , isSub ) {
            var opt = "";
            switch ( this.ValidatorData.ComparisonOperator ) {
                case ComparisonOperator.Equal:
                    opt = "==";
                    break;
                case ComparisonOperator.GreaterThan:
                    opt = ">";
                    break;
                case ComparisonOperator.GreaterThanEqual:
                    opt = ">=";
                    break;
                case ComparisonOperator.LessThan:
                    opt = "<";
                    break;
                case ComparisonOperator.LessThanEqual:
                    opt = "<=";
                    break;
                case ComparisonOperator.NotEqual:
                    opt = "!=";
                    break;
            }
            this.AddRule ( RuleKeys.Operator , string.Format ( "'{0}'" , opt ) );
            //从 Map 里找到要比较的属性对应的控件名称
            // PropertyCompare 只接受同一类时的 Property
            var target = this.Map.Where ( m => m.Value.Item1.EndsWith ( string.Format ( ".{0}" , this.ValidatorData.PropertyToCompare ) ) ).FirstOrDefault ( );
            if ( target.Key != null ) {
                var targetControl = target.Key;
                var targetLabel = target.Value.Item2;
                this.AddRule ( RuleKeys.To , string.Format ( "'{0}'" , targetControl ) );
                this.AddRule ( RuleKeys.TargetLabel , string.Format ( "'{0}'" , targetLabel ) );
            }
        }

        public override RuleTypes RuleType {
            get {
                return RuleTypes.Compare;
            }
        }
    }
}
